package org.tinygroup.fizzbuzzwhizz;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by luoguo on 2014/5/6.
 */
public final class NumberReaderEngine {
    private List<NumberReader> numberReaders = new ArrayList<NumberReader>();

    public void add(NumberReader numberReader) {
        numberReaders.add(numberReader);
    }

    /**
     * 在调用readNumber之前必须调用sortNumberReader
     */
    public void sortNumberReader() {
        Collections.sort(numberReaders);
    }

    public void readNumber(int number) {
        executeReadNumber(number);
        System.out.print(" ");
    }

    private void executeReadNumber(int number) {
        int readPriority = -1;
        for (NumberReader numberReader : numberReaders) {
            //如果已经有读过，且当前优先级与已经读过的优先级不同，则结束
            if (readPriority != -1 && numberReader.getPriority() != readPriority) {
                return;
            }
            boolean isRead = numberReader.read(number);
            if (isRead) {
                if (numberReader.isExclusive()) {
                    //如果是独占方式，且已读，则直接返回
                    return;
                } else {
                    readPriority = numberReader.getPriority();
                }
            }
        }
    }
}
